/*
 * @lc app=leetcode.cn id=703 lang=typescript
 *
 * [703] 数据流中的第 K 大元素
 */

// @lc code=start

class KthLargest {
    cache: number[] = [];
    size = 0;
    constructor(k: number, nums: number[]) {
        nums.forEach((i) => {
            this.add(i);
        });
        this.size = k;
    }
    get lastData() {
        return this.cache[this.size - 1];
    }
    add(val: number): number {
        if (this.lastData === undefined || val > this.lastData) {
            const index = this.cache.findIndex((i) => {
                if (val >= i) {
                    return true;
                }
            });
            if (index === -1) {
                this.cache.push(val);
            } else {
                this.cache.splice(index, 0, val);
            }
        }
        return this.lastData;
    }
}

/**
 * Your KthLargest object will be instantiated and called as such:
 * var obj = new KthLargest(k, nums)
 * var param_1 = obj.add(val)
 */
// @lc code=end
